package thread;

/**
 * @author Dianzhi Han
 * @version 1.0
 * @description: 通过共享变量中断线程（第一种方法）
 * @date 2022/10/27 23:01
 */
public class ThreadInterruptByVar {
    private static class MyThread implements Runnable {
        // 多个线程都会用到的变量加上volatile关键字
        // 当前线程是否需要停止
        volatile boolean isQuit = false;
        @Override
        public void run() {
            while (!isQuit) {
                System.out.println(Thread.currentThread().getName() + "别烦我，我正在给铭哥转账呢~");
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            System.out.println(Thread.currentThread().getName() + "被中断了~");
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThread mt = new MyThread();
        Thread thread = new Thread(mt,"鹏哥线程");
        System.out.println("鹏哥可以开始转账了~~");
        thread.start();
        // 主线程暂停3s，暂停thread
        Thread.sleep(3000);
        System.out.println("鹏哥钱转完了，让他停止！");
        mt.isQuit = true;
    }
}